package cn.action;

import java.io.File;
import java.util.UUID;

import net.sf.json.JSONObject;

import org.apache.commons.io.FileUtils;
import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.Action;

public class FileAction implements Action {
	private File image; //上传的文件
    private String imageFileName; //文件名称
    private String imageContentType; //文件类型
    private String imgFrom;//图片来源
    private String imgPath;//图片路径

    private String resultStr = "";

	public File getImage() {
		return image;
	}

	public void setImage(File image) {
		this.image = image;
	}

	public String getImageFileName() {
		return imageFileName;
	}

	public void setImageFileName(String imageFileName) {
		this.imageFileName = imageFileName;
	}

	public String getImageContentType() {
		return imageContentType;
	}

	public void setImageContentType(String imageContentType) {
		this.imageContentType = imageContentType;
	}

	public String getImgFrom() {
		return imgFrom;
	}

	public void setImgFrom(String imgFrom) {
		this.imgFrom = imgFrom;
	}

	public String getImgPath() {
		return imgPath;
	}

	public void setImgPath(String imgPath) {
		this.imgPath = imgPath;
	}

	public String getResultStr() {
		return resultStr;
	}

	public void setResultStr(String resultStr) {
		this.resultStr = resultStr;
	}

	@Override
	public String execute() throws Exception {
		String realpath = ServletActionContext.getServletContext().getRealPath("/uploadImg");
		if("userInfo".equals(imgFrom)){
			realpath = realpath+"/userImg";
			imgFrom = "userImg/";
		}
		if("goodsEdit".equals(imgFrom)){
			realpath = realpath+"/goodsImg";
			imgFrom = "goodsImg/";
		}
        JSONObject json = new JSONObject();
        if(!(imageFileName.endsWith(".jpg")||imageFileName.endsWith(".bmp"))){
            json.put("message", "对不起,请您上传jpg或bmp格式的图片!!!");
            json.put("flag", "error");
            resultStr = json.toString();
        	return SUCCESS;
        }
        String uuid = UUID.randomUUID().toString().replace("-", "");
        String[] temp = imageFileName.split("\\.");
        imageFileName = uuid+"."+temp[temp.length-1];
        if (image != null) {
            File savefile = new File(new File(realpath), imageFileName);
            if (!savefile.getParentFile().exists())
                savefile.getParentFile().mkdirs();
            FileUtils.copyFile(image, savefile);
            json.put("message", "图片上传成功");
            json.put("flag", "success");
            json.put("imgPath", "uploadImg/"+imgFrom+imageFileName);
            resultStr = json.toString();
        }
		return SUCCESS;
	}

}
